package com.ruoyi.web.controller;

import com.alibaba.fastjson.JSONObject;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.PdfDocument;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.web.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author ：chen
 * @date ：Created in 2019/10/30 14:39
 */
@Controller
@RequestMapping(value="/document")
public class DocumentController {
    @Autowired
    private FileService fileService;

    @RequestMapping(value="/upload")
    @ResponseBody
    public String uploadDocument(MultipartFile document, HttpServletRequest request){
        JSONObject result = new JSONObject();
        result.put("code","0001");
        result.put("msg","未知错误");
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //验证IP
//        boolean checkIp = businessSysService.checkBusinessSysByIp(ip);
        //如果ip不存在
//        if (!checkIp){
//            result.put("code","0005");
//            result.put("msg","服务器IP没有权限");
//            return result.toString();
//        }
        //生成UUID作为文档编码
        //文档保存同步
        String documentCode = IdUtils.simpleUUID();
        result = fileService.saveDocument(document,documentCode);
        return result.toString();
    }
    /**
     * pdf文件下载接口
     * @param documentCode 文档编码
     * @throws IOException 异常
     */
    @RequestMapping(value="/download")
    public void downloadDocument(String documentCode, HttpServletResponse response){
        PdfDocument pdfDocument = fileService.getPDFDocument(documentCode);
        byte[] bytes = null;
        String resultName = null;
        try{
            bytes = fileService.downloadDocument(documentCode, Constants.SIGN_PDF_SUFFIX);
            resultName = new String((pdfDocument.getDocumentname()+"."+Constants.SIGN_PDF_SUFFIX).getBytes(),
                    StandardCharsets.ISO_8859_1);
            //设置MIME类型
            response.setContentType("application/octet-stream");
            //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
            response.addHeader("Content-disposition", "attachment;filename="+ resultName);
            //将文件流输出
            ServletOutputStream outputStream=response.getOutputStream();
            InputStream inputStream = FileUtils.byte2Input(bytes);
            int ch;
            while ((ch = inputStream.read()) != -1) {
                outputStream.write(ch);
            }
            outputStream.close();
            inputStream.close();
            fileService.deleteDocument(documentCode, Constants.SIGN_PDF_SUFFIX);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * pdf文件下载接口
     * @param documentCode 文档编码
     * @throws IOException 异常
     */
    @RequestMapping(value="/ofd/download")
    public void downloadOFDDocument(String documentCode, HttpServletResponse response){
        PdfDocument pdfDocument = fileService.getPDFDocument(documentCode);
        byte[] bytes = null;
        String resultName = null;
        try{
            bytes = fileService.downloadDocument(documentCode, Constants.SIGN_OFD_SUFFIX);
            resultName = new String((pdfDocument.getDocumentname()+"."+Constants.SIGN_OFD_SUFFIX).getBytes(),
                    StandardCharsets.ISO_8859_1);
            //设置MIME类型
            response.setContentType("application/octet-stream");
            //设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
            response.addHeader("Content-disposition", "attachment;filename="+ resultName);
            //将文件流输出
            ServletOutputStream outputStream=response.getOutputStream();
            InputStream inputStream = FileUtils.byte2Input(bytes);
            int ch;
            while ((ch = inputStream.read()) != -1) {
                outputStream.write(ch);
            }
            outputStream.close();
            inputStream.close();
            fileService.deleteDocument(documentCode, Constants.SIGN_PDF_SUFFIX);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
